<template>
  <div class="app-container">
    <div class="module-title">
      <svg-icon icon-class="money" style="font-size:28px;margin-right:8px;"/>
      <span>应付款明细</span>
      <span class="module-desc">管理所有应付账款明细</span>
    </div>
    <div class="module-card">
      <!-- 财务统计卡片 -->
      <div class="finance-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card total-payable">
              <div class="stat-icon">
                <i class="el-icon-money"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">¥{{ formatAmount(totalPayable) }}</div>
                <div class="stat-label">总应付金额</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card total-paid">
              <div class="stat-icon">
                <i class="el-icon-circle-check"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">¥{{ formatAmount(totalPaid) }}</div>
                <div class="stat-label">已付金额</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card total-balance">
              <div class="stat-icon">
                <i class="el-icon-warning"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">¥{{ formatAmount(totalBalance) }}</div>
                <div class="stat-label">应付余额</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card overdue-amount">
              <div class="stat-icon">
                <i class="el-icon-circle-close"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">¥{{ formatAmount(overdueAmount) }}</div>
                <div class="stat-label">逾期金额</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="入库单号" prop="entryCode">
          <el-input
            v-model="queryParams.entryCode"
            placeholder="请输入入库单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="供应商" prop="supplierName">
          <el-input
            v-model="queryParams.supplierName"
            placeholder="请输入供应商名称"
            prefix-icon="el-icon-user"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="付款状态" prop="paymentStatus">
          <el-select v-model="queryParams.paymentStatus" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="未付款" value="未付款" />
            <el-option label="部分付款" value="部分付款" />
            <el-option label="已付款" value="已付款" />
            <el-option label="逾期" value="逾期" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['payable:payable:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['payable:payable:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['payable:payable:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['payable:payable:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="payableList" @selection-change="handleSelectionChange" 
        stripe border size="small" :default-sort="{prop: 'documentDate', order: 'descending'}">
        <el-table-column type="selection" width="45" align="center" />
        <el-table-column label="单据类型" align="center" prop="documentType" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="getDocumentTypeType(scope.row.documentType)" size="mini">
              {{ getDocumentTypeLabel(scope.row.documentType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入库单号" align="center" prop="entryCode" min-width="120" />
        <el-table-column label="单据日期" align="center" prop="documentDate" min-width="100" sortable>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.documentDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供应商名称" align="center" prop="supplierName" min-width="120" />
        <el-table-column label="数量" align="center" prop="quantity" min-width="80">
          <template slot-scope="scope">
            <span class="quantity-amount">{{ scope.row.quantity || '0' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="付款方式" align="center" prop="paymentMethod" min-width="100" />
        <el-table-column label="税额" align="center" prop="taxAmount" min-width="100">
          <template slot-scope="scope">
            <span class="tax-amount">¥{{ formatAmount(scope.row.taxAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应付金额" align="center" prop="payableAmount" min-width="120" sortable>
          <template slot-scope="scope">
            <span class="payable-amount">¥{{ formatAmount(scope.row.payableAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="已付金额" align="center" prop="paidAmount" min-width="120">
          <template slot-scope="scope">
            <span class="paid-amount">¥{{ formatAmount(scope.row.paidAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应付余额" align="center" prop="balanceAmount" min-width="120">
          <template slot-scope="scope">
            <span class="balance-amount" :class="getBalanceAmountClass(scope.row)">
              ¥{{ formatAmount(scope.row.balanceAmount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="付款状态" align="center" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="getPaymentStatusType(scope.row)" size="mini">
              {{ getPaymentStatusLabel(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="150" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['payable:payable:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['payable:payable:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改应付款明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据类型" prop="documentType">
                 <el-select v-model="form.documentType" placeholder="请选择单据类型">
                 <el-option label="1：采购入库" :value="1"></el-option>
                 <el-option label="2：退货入库" :value="2"></el-option>
                 <el-option label="3：其他入库" :value="3"></el-option>
               </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单号" prop="entryCode">
              <el-input v-model="form.entryCode" placeholder="请输入入库单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据日期" prop="documentDate">
              <el-date-picker clearable
                v-model="form.documentDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择单据日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-input v-model="form.paymentMethod" placeholder="请输入付款方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="税额" prop="taxAmount">
              <el-input v-model="form.taxAmount" placeholder="请输入税额">
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应付金额" prop="payableAmount">
              <el-input v-model="form.payableAmount" placeholder="请输入应付金额">
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="已付金额" prop="paidAmount">
              <el-input v-model="form.paidAmount" placeholder="请输入已付金额">
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应付余额" prop="balanceAmount">
              <el-input v-model="form.balanceAmount" placeholder="自动计算" disabled>
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPayable, getPayable, delPayable, addPayable, updatePayable } from "@/api/payable/payable"

export default {
  activated() {
    this.getList()
  },
  name: "Payable",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应付款明细表格数据
      payableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        entryCode: null,
        supplierName: null,
        paymentStatus: null,
        dateRange: []
      },
      // 财务统计数据
      totalPayable: 0,
      totalPaid: 0,
      totalBalance: 0,
      overdueAmount: 0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 日期选择器快捷选项
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询应付款明细列表 */
    getList() {
      this.loading = true
      listPayable(this.queryParams).then(response => {
        this.payableList = response.rows
        this.total = response.total
        this.calculateFinanceStats()
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        documentType: null,
        entryCode: null,
        documentDate: null,
        supplierName: null,
        quantity: null,
        paymentMethod: null,
        taxAmount: null,
        payableAmount: null,
        paidAmount: null,
        balanceAmount: null,
        status: null,
        remark: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.paymentStatus = null
      this.queryParams.dateRange = []
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push('/payable/payable/add')
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPayable(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改应付款明细"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePayable(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPayable(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除应付款明细编号为"' + ids + '"的数据项？').then(function() {
        return delPayable(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('payable/payable/export', {
        ...this.queryParams
      }, `payable_${new Date().getTime()}.xlsx`)
    },
    
    /** 计算财务统计数据 */
    calculateFinanceStats() {
      this.totalPayable = this.payableList.reduce((sum, item) => sum + (parseFloat(item.payableAmount) || 0), 0);
      this.totalPaid = this.payableList.reduce((sum, item) => sum + (parseFloat(item.paidAmount) || 0), 0);
      this.totalBalance = this.payableList.reduce((sum, item) => sum + (parseFloat(item.balanceAmount) || 0), 0);
      
      // 计算逾期金额（超过30天的应付余额）
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
      
      this.overdueAmount = this.payableList.reduce((sum, item) => {
        if (new Date(item.documentDate) < thirtyDaysAgo && parseFloat(item.balanceAmount) > 0) {
          return sum + parseFloat(item.balanceAmount);
        }
        return sum;
      }, 0);
    },
    
    /** 格式化金额 */
    formatAmount(amount) {
      if (!amount || amount === 0) return '0.00';
      return parseFloat(amount).toFixed(2);
    },
    
    /** 获取单据类型标签类型 */
    getDocumentTypeType(type) {
      switch(type) {
        case 1: return 'primary';   // 采购入库
        case 2: return 'warning';   // 退货入库
        case 3: return 'info';      // 其他入库
        default: return 'info';
      }
    },
    
    /** 获取单据类型标签文本 */
    getDocumentTypeLabel(type) {
      switch(type) {
        case 1: return '采购入库';
        case 2: return '退货入库';
        case 3: return '其他入库';
        default: return '未知';
      }
    },
    
    /** 获取付款状态类型 */
    getPaymentStatusType(row) {
      const balance = parseFloat(row.balanceAmount) || 0;
      const paid = parseFloat(row.paidAmount) || 0;
      
      if (balance === 0) return 'success';      // 已付款
      if (paid > 0) return 'warning';           // 部分付款
      if (this.isOverdue(row.documentDate)) return 'danger'; // 逾期
      return 'info';                            // 未付款
    },
    
    /** 获取付款状态标签 */
    getPaymentStatusLabel(row) {
      const balance = parseFloat(row.balanceAmount) || 0;
      const paid = parseFloat(row.paidAmount) || 0;
      
      if (balance === 0) return '已付款';
      if (paid > 0) return '部分付款';
      if (this.isOverdue(row.documentDate)) return '逾期';
      return '未付款';
    },
    
    /** 判断是否逾期 */
    isOverdue(documentDate) {
      if (!documentDate) return false;
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
      return new Date(documentDate) < thirtyDaysAgo;
    },
    
    /** 获取余额金额样式类 */
    getBalanceAmountClass(row) {
      const amount = parseFloat(row.balanceAmount) || 0;
      if (amount === 0) return 'amount-zero';
      if (this.isOverdue(row.documentDate)) return 'amount-overdue';
      return 'amount-normal';
    },
    
    /** 查看详情 */
    handleView(row) {
      this.$router.push({
        path: '/payable/payable/detail',
        query: { id: row.id }
      });
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/assets/styles/module-card.scss";

.module-title {
  display: flex;
  align-items: center;
  font-size: 22px;
  font-weight: 700;
  color: #2980b9;
  margin-bottom: 18px;
  .module-desc {
    font-size: 14px;
    color: #888;
    font-weight: 400;
    margin-left: 18px;
  }
}

.tax-amount {
  color: #f39c12;
  font-weight: 500;
}

.payable-amount {
  color: #e74c3c;
  font-weight: 600;
}

.paid-amount {
  color: #27ae60;
  font-weight: 600;
}

.balance-amount {
  color: #2980b9;
  font-weight: 700;
  font-size: 14px;
}

.quantity-amount {
  color: #3498db;
  font-weight: 600;
  font-size: 14px;
}

.el-table {
  .el-table__body tr:hover > td {
    background: #eaf6ff !important;
  }
}

.el-dialog {
  .el-form-item {
    margin-bottom: 20px;
  }

  .el-input-group__prepend {
    background: #f0f4fa;
    color: #2980b9;
    font-weight: 600;
    border-color: #dbeafe;
  }
}

// 财务统计卡片样式
.finance-stats {
  margin-bottom: 24px;
  
  .stat-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16px;
    padding: 24px;
    color: white;
    display: flex;
    align-items: center;
    transition: transform 0.3s ease;
    
    &:hover {
      transform: translateY(-4px);
    }
    
    &.total-payable {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }
    
    &.total-paid {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
    
    &.total-balance {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
    
    &.overdue-amount {
      background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
    }
    
    .stat-icon {
      font-size: 48px;
      margin-right: 20px;
      opacity: 0.8;
    }
    
    .stat-content {
      .stat-number {
        font-size: 28px;
        font-weight: 700;
        line-height: 1;
        margin-bottom: 8px;
      }
      
      .stat-label {
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }
}

// 表格样式优化
.el-table {
  .el-table__body tr:hover > td {
    background: #eaf6ff !important;
  }
  
  .quantity-amount {
    font-weight: 600;
    color: #409EFF;
  }
  
  .tax-amount {
    font-weight: 600;
    color: #E6A23C;
  }
  
  .payable-amount {
    font-weight: 700;
    color: #F56C6C;
  }
  
  .paid-amount {
    font-weight: 600;
    color: #67C23A;
  }
  
  .balance-amount {
    font-weight: 700;
    
    &.amount-zero {
      color: #67C23A;
    }
    
    &.amount-overdue {
      color: #F56C6C;
    }
    
    &.amount-normal {
      color: #E6A23C;
    }
  }
}

// 表格容器样式优化
.module-card {
  .el-table {
    width: 100%;
    
    .el-table__body-wrapper {
      overflow-x: auto;
    }
    
    .el-table__header-wrapper {
      overflow-x: auto;
    }
  }
}

// 搜索表单优化
.el-form--inline .el-form-item {
  margin-bottom: 16px;
}

// 响应式优化
@media (max-width: 1200px) {
  .finance-stats {
    .el-col {
      margin-bottom: 16px;
    }
  }
  
  .el-table {
    .el-table__body-wrapper {
      overflow-x: auto;
    }
  }
}

@media (max-width: 768px) {
  .el-table {
    font-size: 12px;
    
    .el-table__body-wrapper {
      overflow-x: auto;
    }
  }
  
  .finance-stats {
    .stat-card {
      padding: 16px;
      
      .stat-icon {
        font-size: 32px;
        margin-right: 12px;
      }
      
      .stat-content {
        .stat-number {
          font-size: 20px;
        }
        
        .stat-label {
          font-size: 12px;
        }
      }
    }
  }
}
</style>
